package com.fingard.dsp.bank.directbank.bocom13;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IRealTime;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Date;

/**
 * 交通银行资金清算平台单笔代扣
 *
 * 参考文档:
 * 		1、交通银行资金清算平台联机交易接口V1.0.doc
 * 		2、交通银行资金清算平台数据字典V1.0.doc
 *
 * @author Cruise
 * @date 2019/4/18
 */
public class BOCOM13RealTime extends BOCOM13Base implements IRealTime {
    /**
     * 开发接口:4.4	代收付（I00404）
     */
    @Override
    public RetAtsSingle d_9108_RealTimeRec(ReqSingle p_req9108) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req9108.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
        tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
        try {
            BOCOM13Header tmpBankHeader = new BOCOM13Header();
            tmpBankHeader.transCode = BOCOM13TransCode.singleRec_9108_910801;
            tmpBankHeader.reqSeqID = p_req9108.singleDetail.askNumber;
            String corpNo = getBankConfig().getMapValueByKey("corpNoMapping", p_req9108.singleDetail.recAct);
            if (StringHelper.isNullOrEmpty(corpNo)) {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = "未找到账号[" + p_req9108.singleDetail.recAct + "]保险方ID映射,请检查BOCOM13/config.xml中'corpNoMapping'节点配置";
                tmpRetDetail.transState = PaymentState.FAIL_Payment;
                tmpRetDetail.payInfoCode = FailCode.E9981;
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            tmpBankHeader.corpNo = corpNo;
            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter, tmpBankHeader);
            xmlWriter.writeStartElement("Body");
            xmlWriter.writeElementString("BusDate", Format.Date8Format.format(new Date()));/* 保险方业务日期 */
            xmlWriter.writeElementString("SeqNo", tmpBankHeader.reqSeqID);/* 保险方流水号 */
            xmlWriter.writeElementString("ApplyNo", p_req9108.singleDetail.oriSourceNoteCode);/* 投保单号 */
            xmlWriter.writeElementString("PolNo", p_req9108.singleDetail.insuPolicyNum);/* 保单号 */
            xmlWriter.writeElementString("Name", p_req9108.singleDetail.payName);/* 客户姓名 */
            xmlWriter.writeElementString("IdType", convertCertTypeToBank(p_req9108.singleDetail.certType));/* 证件类型 */
            xmlWriter.writeElementString("IdNo", p_req9108.singleDetail.certNum);/* 证件号码 */
            xmlWriter.writeElementString("Telephone", p_req9108.singleDetail.cellPhone);/* 手机号码 */
            String isPrivate = "";
            if ("1".equals(p_req9108.singleDetail.isPrivate)) {
                isPrivate = "P";
            } else {
                isPrivate = "E";
            }
            xmlWriter.writeElementString("EpFlag", isPrivate);/* 公私标志(E-对公,P-对私) */
            xmlWriter.writeElementString("PrdName", "");/* 险种名称 */
            String sameBnk = "1".equals(p_req9108.singleDetail.sameBnk)? "1" : "2";
            xmlWriter.writeElementString("BkFlag", sameBnk);
            xmlWriter.writeElementString("BkNo", p_req9108.singleDetail.cnapsCode);/* 收款行行号 */
            xmlWriter.writeElementString("ActNo", p_req9108.singleDetail.payAct);/* 账号 */
            xmlWriter.writeElementString("CurType", "CNY");/* 交易币种 */
            xmlWriter.writeElementString("Amt", p_req9108.singleDetail.payAmount);/* 交易金额 */
            String businessType = getBankConfig().getSetValue("businessType", "Usage", "9108");
            if (StringHelper.hasAnyChar(businessType)) {
                businessType = getBankConfig().getMapValueByKey("recBusiCode", p_req9108.singleDetail.srcXElement.getSingleText(businessType));
            }
            if (StringHelper.isNullOrEmpty(businessType)) {
                businessType = "D10";// 默认为首期缴费
            }
            xmlWriter.writeElementString("BusType", businessType);/* 收付种类:2.42收付种类*/
            xmlWriter.writeElementString("AgreementNo", p_req9108.singleDetail.authCode);/* 代收协议编号 */
            xmlWriter.writeElementString("Ext001", "");
            xmlWriter.writeElementString("Ext002", "");
            xmlWriter.writeElementString("Ext003", "");
            xmlWriter.writeElementString("Ext004", "");
            xmlWriter.writeElementString("Ext005", "");
            xmlWriter.writeElementString("Ext006", "");
            xmlWriter.writeElementString("Ext007", "");
            xmlWriter.writeElementString("Ext008", "");
            xmlWriter.writeElementString("Ext009", "");
            xmlWriter.writeElementString("Ext010", "");
            xmlWriter.writeEndDocument();
            String[] tmpRetStr = sendToBank(xmlWriter.toXmlString(), bankFront.serverPort);
            if (tmpRetStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    tmpRetDetail.respCode = "0";
                    String tmpErrMsg=tmpBkReader.getFirstText("/Rsp/Head/ErrMsg");
                    tmpRetDetail.respInfo = tmpErrMsg;
                    String tmpMsgType = tmpBkReader.getFirstText("/Rsp/Head/MsgType");
                    String tmpErrCode = tmpBkReader.getFirstText("/Rsp/Head/ErrCode");
                    String transState = tmpBkReader.getFirstText("/Rsp/Body/BusStat");
                    if ("N".equals(tmpMsgType) && "000000".equals(tmpErrCode)&&("1".equals(transState) ||"0".equals(transState))) {
                        // 交易状态:0-处理中 1-成功  2-失败 3-超时
                        tmpRetDetail.transState = "D+" + transState;/* 交易状态 */
                        tmpRetDetail.payInfoCode = tmpErrCode;
                        String tmpRepMsg=tmpBkReader.getFirstText("/Rsp/Body/RepMsg");
                        if (StringHelper.hasAnyChar(tmpRepMsg)) {
                            tmpRetDetail.respInfo = tmpRepMsg;
                        }
                    } else if("E".equals(tmpMsgType) &&"2".equals(transState)){
                        tmpRetDetail.transState = "D+"+transState;/* 交易状态 */
                    }else {
                        tmpRetDetail.respCode = "-1";
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpRetStr[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    /**
     * 开发接口：4.6	代收付交易查证（I00405）
     */
    @Override
    public RetAtsSingle d_9144_QryRealTimeRec(ReqQrySingle p_req9144) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req9144.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
        tmpRetDetail.reqSeqID = p_req9144.askNumber;

        try {
            BOCOM13Header tmpBankHeader = new BOCOM13Header();
            tmpBankHeader.transCode = BOCOM13TransCode.singleRec_9144_910801;
            tmpBankHeader.reqSeqID = p_req9144.askNumber;

            String corpNo = getBankConfig().getMapValueByKey("corpNoMapping", p_req9144.recAct);
            if (StringHelper.isNullOrEmpty(corpNo)) {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = "未找到账号[" + p_req9144.recAct + "]保险方ID映射,请检查BOCOM13/config.xml中'corpNoMapping'节点配置";
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            tmpBankHeader.corpNo = corpNo;

            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter, tmpBankHeader);

            xmlWriter.writeStartElement("Body");
            xmlWriter.writeElementString("BusDate", Format.Date8Format.format(p_req9144.getBgnDateTime()));/* 保险方业务日期 */
            xmlWriter.writeElementString("SeqNo", tmpBankHeader.reqSeqID);/* 保险方原流水号 */
            xmlWriter.writeEndDocument();

            String[] tmpRetStr = sendToBank(xmlWriter.toXmlString(), bankFront.serverPort);
            if (tmpRetStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    tmpRetDetail.respCode = "0";
                    String tmpErrMsg=tmpBkReader.getFirstText("/Rsp/Head/ErrMsg");
                    tmpRetDetail.respInfo =tmpErrMsg;
                    String tmpMsgType = tmpBkReader.getFirstText("/Rsp/Head/MsgType");
                    String tmpErrCode = tmpBkReader.getFirstText("/Rsp/Head/ErrCode");
                    String tmpBusStat=tmpBkReader.getFirstText("/Rsp/Body/BusStat");
                    String tmpRepMsg=tmpBkReader.getFirstText("/Rsp/Body/RepMsg");
                    String tmpRepCode=tmpBkReader.getFirstText("/Rsp/Body/RepCode");
                    if ("N".equals(tmpMsgType) && "000000".equals(tmpErrCode)) {
                        // 交易状态:0-处理中 1-成功  2-失败 3-超时
                        tmpRetDetail.transState = "D+" + tmpBusStat;/* 交易状态 */
                        tmpRetDetail.payInfoCode = tmpBkReader.getFirstText("/Rsp/Body/RepCode");

                    }else if(tmpErrMsg.contains("交易记录不存在")){
                        tmpRetDetail.respCode = "0";
                        tmpRetDetail.transState = "D+2";
                        tmpRetDetail.payInfoCode = tmpRepCode;

                    }else if(StringHelper.hasAnyChar(tmpBusStat)){
                        tmpRetDetail.transState = "D+" + tmpBusStat;
                        tmpRetDetail.payInfoCode = tmpRepCode;
                    }
                    else {
                        tmpRetDetail.respCode = "-1";
                    }
                    if (StringHelper.hasAnyChar(tmpRepMsg)) {
                        tmpRetDetail.respInfo = tmpRepMsg;
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpRetStr[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }
}